/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.me.SendSMS;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

import org.me.SendSMS.utli.GlobalVariable;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.PowerManager;
import android.os.RemoteException;
import android.os.PowerManager.WakeLock;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.Toast;

public class AlarmService extends Service {
	
	
	private static final String TAG 			= "MyService";
	String date_loop							= "";
	String date_repeat							= "";
	boolean test 								= false;
	String checkeverydate						= "";
	String picktime 							= "";
	String number 								= "";
	String numberRepeat							= "";
	String message 								= "";
	String messageRepeat						= "";
	String time 								= "";
	String timeloop								= "";
	String random								= "";
	public static int TIME 						= 30000;	
	String date 								= "";
	public static boolean isRunService 			= false;
	boolean checkSend 							= true;
	boolean checkSend1							= true;
	

	
	String array[];
	public static Thread myService;
	private  Calendar cal;
	private  SimpleDateFormat sdf;
	public  String FORMAT_DATE_TIME;
	private ThreadGroup myThreads = new ThreadGroup("ServiceWorker");
	private WakeLock wakeLock;
	
	
	
    // Defines a label for the thread that this service starts
    private static final String ALARM_SERVICE_THREAD = "AlarmService";

    // Defines 15 seconds
    public static final long WAIT_TIME_SECONDS = 5;

    // Define the number of milliseconds in one second
    public static final long MILLISECS_PER_SEC = 300;




    // A Binder, used as the lock object for the worker thread.
    IBinder mBinder = new AlarmBinder();

    // A Thread object that will run the background task
    Thread mWorkThread;

    // The Runnable that is the service's "task". This illustrates how a service is used to
    // offload work from a client.
    Runnable mWorkTask = new Runnable() {
        public void run() {
            // Sets the wait time to 15 seconds, simulating a 15-second background task.
            long waitTime = System.currentTimeMillis() + WAIT_TIME_SECONDS * MILLISECS_PER_SEC;

            while (System.currentTimeMillis() < waitTime) {
                // Waits for 15 seconds or interruption
                synchronized (mBinder) {
                    try {
                        mBinder.wait(waitTime - System.currentTimeMillis());
                    } catch (InterruptedException e) {
                    }
                }
            }
            // Stops the current service. In response, Android calls onDestroy().
            stopSelf();
        }
    };

    /**
     *  Makes a full concrete subclass of Binder, rather than doing it in line, for readability.
     */
    public class AlarmBinder extends Binder {
        // Constructor. Calls the super constructor to set up the instance.
        public AlarmBinder() {
            super();
        }

        @Override
        protected boolean onTransact(int code, Parcel data, Parcel reply, int flags)
            throws RemoteException {

            // Call the parent method with the arguments passed in
            return super.onTransact(code, data, reply, flags);
        }
    }

    @Override
    public void onCreate() {
    	
    	Log.e(TAG, "onCreate");
		random				= GlobalVariable.getValueKeyString(getApplicationContext(), GlobalVariable.random);
		Log.e("onCreate", "random = "+random);
		date_repeat			= GlobalVariable.getValueKeyString(getApplicationContext(), GlobalVariable.dateRepeat);
		Log.e("onCreate", "date_repeat = "+date_repeat);
		checkeverydate		= GlobalVariable.getValueKeyString(getApplicationContext(), GlobalVariable.checkeverydate);
		Log.e("onCreate", "checkeverydate = "+checkeverydate);
		picktime			= GlobalVariable.getValueKeyString(getApplicationContext(), GlobalVariable.picktime);
		Log.e("onCreate", "picktime = "+picktime);
		time 				= GlobalVariable.getValueKeyString(getApplicationContext(), GlobalVariable.time);
		Log.e("onCreate", "time = "+time);
		timeloop			= GlobalVariable.getValueKeyString(getApplicationContext(), GlobalVariable.timeloop);
		Log.e("onCreate", "timeloop = "+timeloop);
		date 				= GlobalVariable.getValueKeyString(getApplicationContext(), GlobalVariable.date);
		Log.e("onCreate", "date = "+date);
		number 				= GlobalVariable.getValueKeyString(getApplicationContext(), GlobalVariable.number);
		Log.e("onCreate", "number = "+number);
		message 			= GlobalVariable.getValueKeyString(getApplicationContext(), GlobalVariable.message);
		Log.e("onCreate", "message = "+message);
		numberRepeat		= GlobalVariable.getValueKeyString(getApplicationContext(), GlobalVariable.numberRepeat);
		Log.e("onCreate", "numberRepeat = "+numberRepeat);
		messageRepeat		= GlobalVariable.getValueKeyString(getApplicationContext(), GlobalVariable.messageRepeat);
		Log.e("onCreate", "messageRepeat = "+messageRepeat);
		cal 				= null;
		sdf 				= null;	
		FORMAT_DATE_TIME 	= "yyyy-MM-dd HH:mm:ss";
		
		try
		{
			Log.e("met", "checkeverydate = "+checkeverydate);
			Log.e("met", "picktime = "+picktime);
			if(picktime!=null && picktime.equals("true"))
			{
				Log.w("hung", "time = "+time);
				Log.w("hung", "date = "+date);
    			if(date!=null && SpilitDateForServices().equals(date))
    			{
    				if(time!=null && SpilitTimeForServices().equals(time) && checkSend)
    				{
	    				try {
	    					if(number.split(",").length>0)
	    					{
	    						Log.w("lengh", "number.length = "+number.split(",").length);
	    						for(int i = 0; i< number.split(",").length; i++)
	    						{
			    					SmsManager smsManager = SmsManager.getDefault();
			    					Log.e("hung", "number = "+number.split(",")[i]);
			    					Log.e("hung", "message = "+message);
			    					smsManager.sendTextMessage(number.split(",")[i], null, message, null, null);
			    					Log.e("handle", "da send sms");
			    					createNotification(getApplicationContext(), "Bạn đã gởi tin nhắn đến số điện thoại "+number.split(",")[i]);
			    					Toast.makeText(getApplicationContext(), "SMS Sent!",
			    							Toast.LENGTH_LONG).show();
			    					checkSend = false;
	    						}
	    					}
	    					
	    				} catch (Exception e) {
	    					Toast.makeText(getApplicationContext(),
	    							"SMS faild, please try again later!",
	    							Toast.LENGTH_LONG).show();
	    					e.printStackTrace();
	    				}
    				}
    			}
			}
			
			Log.e("met", "checkeverydate1111111111111 = "+checkeverydate);
			
			if(checkeverydate!=null && checkeverydate.equals("true"))
			{
				Log.e("vo day khong", "co vo nhi");
				if(timeloop!=null &&  date_repeat!=null && SpilitTimeForServices().equals(timeloop) )
				{
					Log.e("vo day khong", "1111");
					for(int i = 0; i<date_repeat.split(",").length; i++)
					{
						Log.e("vo day khong", "2222");
						Log.e("everydate", "daterepeate = "+date_repeat.split(",")[i]);
						if(date_repeat.split(",")[i].equals(ConvertDate()))
						{
							Log.e("vo day khong", "333");
							
							try
							{
								if(numberRepeat.split(",").length>0)
		    					{
									Log.e("vo day khong", "4444");
		    						for(int j = 0; j< numberRepeat.split(",").length; j++)
		    						{
		    							if(messageRepeat!=null)
		    							{
		    								Log.e("vo day khong", "5555");
					    					SmsManager smsManager = SmsManager.getDefault();
					    					Log.e("hung", "number = "+numberRepeat.split(",")[j]);
		    								Log.e("handle", "da send sms");
		    								createNotification(getApplicationContext(), "Bạn đã gởi tin nhắn đến số điện thoại "+number.split(",")[j]);
					    					Log.e("hung", "messageRepeat = "+messageRepeat);
					    					smsManager.sendTextMessage(numberRepeat.split(",")[j], null, messageRepeat, null, null);
					    					Toast.makeText(getApplicationContext(), "SMS Sent!",
				    						Toast.LENGTH_LONG).show();
		    							}
		    							else
		    							{
		    								String mess = GetRandomMessage(random);
		    								SmsManager smsManager = SmsManager.getDefault();
		    								Log.e("hung", "number = "+numberRepeat.split(",")[j]);
		    							    Log.e("handle", "da send sms");
		    							    createNotification(getApplicationContext(), "Bạn đã gởi tin nhắn đến số điện thoại "+number.split(",")[j]);
		    								Log.e("hung", "numberRepeat = "+numberRepeat);
		    								Log.e("hung", "messageRepeat = "+mess);
		    								smsManager.sendTextMessage(numberRepeat.split(",")[j], null, mess, null, null);
		    								Toast.makeText(getApplicationContext(), "SMS Sent!",
		    								Toast.LENGTH_LONG).show();
		    							}
		    							checkSend1 = false;
		    						}
		    					}
								
	    				} catch (Exception e) {
	    						Toast.makeText(getApplicationContext(),
	    							"SMS faild, please try again later!",
	    							Toast.LENGTH_LONG).show();
	    						e.printStackTrace();
	    				}
						}
					}
				}
			}
		}
		catch (Exception e)
		{
			//writeFileToLog("myHandle", "myHandle");
		}
	

    	
    	
    	
    	
        mWorkThread = new Thread(
            null,  // threadgroup (in this case, null)
            mWorkTask, // the Runnable that will run in this thread
            ALARM_SERVICE_THREAD
        );
        // Starts the thread
        mWorkThread.start();
        
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNjfdhotDimScreen");

		if(wakeLock != null)
		{
			if(!wakeLock.isHeld())
			{
				wakeLock.acquire();
			}
		}
    }

   
    @Override
    public void onDestroy() {
        // Cancels the status bar mNotification based on its ID, which is set in showNotification().
    }

    // Returns the service's binder object to clients that issue onBind().
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
    
    
    public void createNotification(Context context, String payload) {
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(R.drawable.ic_launcher,
				"Message received", System.currentTimeMillis());
		// Hide the notification after its selected
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		notification.defaults = Notification.DEFAULT_ALL;
		Intent intent = new Intent(context, SendSMSActivity.class);
		Log.e("createNotification", "payload = "+payload);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP |Intent.FLAG_ACTIVITY_NEW_TASK);
		
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
				intent, 0);
		notification.setLatestEventInfo(context, "Message",
				payload, pendingIntent);
		notificationManager.notify(0, notification);

	}
	
	public List<String> GetArray(String array)
	{
		List<String> l = new ArrayList<String>();
		Log.w("GetArray", "s.size = "+array.split("/").length);
		for(int k = 0; k<array.split("/").length; k++)
		{
			l.add(array.split("/")[k]);
		}
		
		return l;
	}
	
	public static int getRandom(int from, int to) {
	    if (from < to)
	        return from + new Random().nextInt(Math.abs(to - from));
	    return from - new Random().nextInt(Math.abs(to - from));
	}
	
	public String GetRandomMessage(String s)
	{
		List<String> list = GetArray(s);
		int i = getRandom(0, list.size());
		Log.w("Get random message", "i = "+i);
		Log.w("Get random message", "list = "+list.get(i));
		return list.get(i);
		
	}
	
	public String ConvertDate()
	{
		try
		{
			DateFormat df1 	= new SimpleDateFormat(FORMAT_DATE_TIME);
	    	DateFormat df2 	= new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'");
	    	date_loop 		= df2.format(df1.parse(getDateTime()));
		}
		catch (Exception e) {
			// TODO: handle exception
		}
		Log.w("ConvertDate", "date_loop = "+date_loop.substring(0, 3));
		return date_loop.substring(0, 3);
	}
	
	public String SpilitTimeForServices()
	{
		String date = getDateTime();
		String []array = date.split(" ");
		String []arrayTime = array[1].split(":");
		Log.w("SpilitTimeForServices", "time = "+arrayTime[0] +":"+ arrayTime[1]);
		return arrayTime[0] +":"+ arrayTime[1];
	}
	
	public String SpilitDateForServices()
	{
		String date = getDateTime();
		String []array = date.split(" ");
		String []arrayDate = array[0].split("-");
		Log.w("SpilitDateForServices", "dateservices = "+arrayDate[2] +"/"+ arrayDate[1]+ "/"+arrayDate[0]);
		return arrayDate[2] + "/"+arrayDate[1] + "/"+arrayDate[0];
		
	}
	
	public String getDateTime()
	{
	    cal = Calendar.getInstance();
	    sdf = new SimpleDateFormat(FORMAT_DATE_TIME);
	    
	    return sdf.format(cal.getTime());
	}


   
}
